package emulator.GUI.util;

import java.awt.Toolkit;
import java.awt.datatransfer.ClipboardOwner;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.StringSelection;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.io.IOException;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import com.jhe.hexed.ClipboardInterface;

public class Clipboard implements ClipboardOwner, ClipboardInterface
{
	static Logger logger = LogManager.getLogger(Clipboard.class.getName());

	@Override
	public void lostOwnership(java.awt.datatransfer.Clipboard aClipboard,
							  Transferable aContents)
	{
		// NOP
	}

	  /* (non-Javadoc)
	 * @see emulator.GUI.util.ClipboardInterface#setClipboardContents(java.lang.String)
	 */
	  @Override
	public void setClipboardContents( String aString ){
	    StringSelection stringSelection = new StringSelection( aString );
	    java.awt.datatransfer.Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
	    clipboard.setContents( stringSelection, this );
	  }

	  /* (non-Javadoc)
	 * @see emulator.GUI.util.ClipboardInterface#getClipboardContents()
	 */
	  @Override
	public String getClipboardContents() {
	    String result = "";
	    java.awt.datatransfer.Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
	    //odd: the Object param of getContents is not currently used
	    Transferable contents = clipboard.getContents(null);
	    boolean hasTransferableText =
	      (contents != null) &&
	      contents.isDataFlavorSupported(DataFlavor.stringFlavor)
	    ;
	    if ( hasTransferableText ) {
	      try {
	        result = (String)contents.getTransferData(DataFlavor.stringFlavor);
	      }
	      catch (UnsupportedFlavorException ex){
	        //highly unlikely since we are using a standard DataFlavor
	        logger.warn("failed to get clipboard content", ex);
	      }
	      catch (IOException ex) {
	        logger.warn("failed to get clipboard content", ex);
	      }
	    }
	    return result;
	  }

}
